package com.csyf.manager.service.impl;

import com.csyf.manager.dao.SysAccountBalanceDao;
import com.csyf.manager.dao.SysAgentBalanceDao;
import com.csyf.manager.entity.SysAccountBalance;
import com.csyf.manager.entity.SysAgentBalance;
import com.csyf.manager.service.SysAccountBalanceBiz;
import com.csyf.manager.utils.DateHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @Author: Enzo
 * @Date: 2018/10/28 17:04
 */
@Slf4j
@Service
public class SysAccountBalanceBizImpl implements SysAccountBalanceBiz {


    @Autowired
    private SysAccountBalanceDao sysAccountBalanceDao;


    @Autowired
    private SysAgentBalanceDao sysAgentBalanceDao;

    @Override
    public BigDecimal queryBalance(String srcmch_id, int day) {

        Calendar instance = Calendar.getInstance();
        //前某天日期
        instance.add(Calendar.DATE, -day);
        String beforeonedate = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());

        SysAccountBalance accountBalance = new SysAccountBalance();
        accountBalance.setMerchantno(srcmch_id);
        accountBalance.setCurdate(beforeonedate);
        SysAccountBalance yesterday = sysAccountBalanceDao.selectOne(accountBalance);

        return null != yesterday ? yesterday.getTotalmoney() : BigDecimal.ZERO;
    }


    @Override
    public void insert(SysAccountBalance vo) {
        sysAccountBalanceDao.insertSelective(vo);
    }

    @Override
    public void addMoney(Long agentId,String mch_id,BigDecimal money,String type) throws Exception{

        log.info("");

        SysAgentBalance example = new SysAgentBalance();
        example.setAgentId(agentId);
        example.setService(type);
        example.setCurdate(DateHelper.getPastDate(1));

        SysAgentBalance sysAgentBalance = sysAgentBalanceDao.selectByPrimaryKey(example);
        if(null == sysAgentBalance){

            example.setTotalprofit(money);
            example.setTotalmoney(money);
            example.setMchId(mch_id);
            sysAgentBalanceDao.insertSelective(example);
        }else{
            example.setTotalmoney(money.add(sysAgentBalance.getTotalmoney()));
            example.setTotalprofit(money.add(sysAgentBalance.getTotalprofit()));
        }

        Example example1 = new Example(SysAgentBalance.class);
        Example.Criteria criteria = example1.createCriteria();
        criteria.andEqualTo("agentId",agentId);
        criteria.andEqualTo("service",type);
        criteria.andEqualTo("curdate",DateHelper.getPastDate(1));

        sysAgentBalanceDao.updateByExampleSelective(example,example1);
    }


}
